/**
 * @Date 2024/12/26 14:20
 * @Created by 衡盛永
 */

package org.example.deploy.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.example.deploy.pojo.SysUser;
import org.example.deploy.service.SysUserService;
import org.example.deploy.dto.ResultDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.example.deploy.vo.user.AddUserVo;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/user")
public class UserController {
    @Autowired
    private SysUserService userService;

    // 自定义 SQL 查询
    @GetMapping("list_xml")
    public List<SysUser> getUsersXml() {
        List<SysUser> usersXml = userService.getUsersXml();
        for (SysUser user : usersXml) {
            System.out.println(user);
        }
        return usersXml;
    }

    @GetMapping("list")
    public ResultDto<IPage<SysUser>> getUsers(@RequestParam Map<String, String> params) {
        System.out.println("params:" + params);
        int current = Integer.parseInt(params.get("page"));
        int size = Integer.parseInt(params.get("size"));
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        // wrapper.eq("username", "user1");
        //参数一current：当前页   参数二size：页面大小
        Page<SysUser> page = new Page<>(current, size);
        IPage<SysUser> page1 = userService.page(page, wrapper);

        // 获取当前页的分页信息
        System.out.println("获取当前页的记录: " + page.getRecords());
        System.out.println("当前页码: " + page.getCurrent());
        System.out.println("每页条数: " + page.getSize());
        System.out.println("总记录数: " + page.getTotal());
        System.out.println("总页数: " + page.getPages());
        System.out.println("是否有下一页: " + page.hasNext());
        System.out.println("是否有上一页: " + page.hasPrevious());
        return ResultDto.success("获取用户列表成功", page);
    }

    @PostMapping("add")
    public ResultDto<Boolean> addUser(@RequestBody AddUserVo addUserVo) {
        SysUser sysUser = new SysUser();
        sysUser.setUsername(addUserVo.getUsername());
        sysUser.setAge(addUserVo.getAge());
        sysUser.setEmail(addUserVo.getEmail());
        sysUser.setPassword("123456"); // 默认密码 123456
        boolean save = userService.save(sysUser);
        return ResultDto.success("新增用户成功", true);
    }

    @PostMapping("update")
    public boolean updateUser(@RequestBody SysUser user) {
        return userService.updateById(user);
    }

    @DeleteMapping("delete/{userId}")
    public ResultDto<Boolean> deleteByUserId(@PathVariable Integer userId) {

        boolean b = userService.removeById(userId);
        if (b) {
            return ResultDto.success("删除用户成功", true);
        } else {
            return ResultDto.error(201, "删除用户失败");
        }
    }
}
